package com.wmlt.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.wmlt.dao.UserDao;
import com.wmlt.dao.impl.UserDaoImpl;
import com.wmlt.entity.Article;
import com.wmlt.entity.ArticleResposeData;
import com.wmlt.entity.LayuiResponseData;
import com.wmlt.entity.User;
import com.wmlt.service.ArticleService;
import com.wmlt.service.UserService;
import com.wmlt.service.impl.ArticleServiceImpl;
import com.wmlt.service.impl.UserServiceImpl;
import com.wmlt.util.GetRequestJsonUtils;
import jdk.nashorn.internal.parser.JSONParser;
import org.apache.commons.lang3.StringEscapeUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;

//文章api
public class ArticleApi extends HttpServlet {
    ArticleService articleService = null;
    List<Article> articleList = null;
    int result;//增删改返回结果
    @Override
    public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        String path = req.getServletPath();
        if ("/article/getAllArticle".equals(path)) {
            getAllArticle(req, res);
        } else if ("/article/deleteArticle".equals(path)) {
            deleteArticle(req, res);
        } else if ("/article/queryArticle".equals(path)) {
            queryArticle(req, res);
        } else if ("/article/queryArticleByArticleId".equals(path)) {
            queryArticleByArticleId(req, res);
        } else if ("/article/readTheArticleController".equals(path)) {
            getListArticles(req, res);
        } else if ("/article/reviewArticle".equals(path)) {
            reviewArticle(req, res);
        } else if ("/article/addArticle".equals(path)) {
            addArticle(req, res);
        } else if ("/article/getTypelookup".equals(path)) {
            getTypelookup(req, res);
        } else if ("/article/getTheArticleByType".equals(path)) {
            getTheArticleByType(req, res);
        } else if ("/article/getArticlesAccordingToProgram".equals(path)) {
            getArticlesAccordingToProgram(req, res);
        }else if("/article/getArticleListByUserId".equals(path)){
            getArticleListByUserId(req, res);
        }
    }

    //获取所有文章
    protected void getAllArticle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/json;charset=utf-8");
        System.out.println("获取文章列表");
        articleService = new ArticleServiceImpl();
        articleList = new ArrayList<Article>();
        articleList = articleService.getAllArticle();
        LayuiResponseData data = new LayuiResponseData();
        data.setCode(200);
        data.setMsg("成功");
        UserDao userDao = new UserDaoImpl();
        data.setCount(userDao.getUserNumber());
        data.setData(articleList);
        String jsonStr = JSON.toJSONString(data);
        response.getWriter().println(jsonStr);

    }

    //删除文章
    protected void deleteArticle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/json;charset=utf-8");
        System.out.println("删除文章");
        articleService = new ArticleServiceImpl();
        articleList = new ArrayList<Article>();
        String[] articleIdArr = request.getParameterValues("articleId[]");
        System.out.println(articleIdArr);
        int result = articleService.deleteArticle(articleIdArr);
        LayuiResponseData data = new LayuiResponseData();
        data.setCode(result);
        data.setMsg("成功");
        UserDao userDao = new UserDaoImpl();
        data.setCount(userDao.getUserNumber());
        data.setData(articleList);
        String jsonStr = JSON.toJSONString(data);
        response.getWriter().println(jsonStr);

    }

    //查询文章，根据文章标题模糊查询
    protected void queryArticle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/json;charset=utf-8");
        System.out.println("查询文章");
        articleService = new ArticleServiceImpl();
        articleList = new ArrayList<Article>();
        articleList = articleService.queryArticle(request.getParameter("articleTitle"));
        LayuiResponseData data = new LayuiResponseData();
        data.setCode(200);
        data.setMsg("成功");
        UserDao userDao = new UserDaoImpl();
        data.setCount(userDao.getUserNumber());
        data.setData(articleList);
        String jsonStr = JSON.toJSONString(data);
        response.getWriter().println(jsonStr);

    }

    //查询文章，根据文章id查询
    protected void queryArticleByArticleId(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/json;charset=utf-8");
        System.out.println("查询文章");
        articleService = new ArticleServiceImpl();
        Article article = new Article();
        article = articleService.queryArticleByArticleId(Integer.parseInt(request.getParameter("articleId")));
        articleService.increaseArticleReading(request.getParameter("articleId"),1);
        String jsonStr = JSON.toJSONString(article);
        System.out.println(jsonStr);
        response.getWriter().println(jsonStr);
        System.out.println("返回数据");
    }


    //获取文章列表
    protected void getListArticles(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取列表
        ArticleService articleService = new ArticleServiceImpl();
        List<Article> articleList = articleService.getToObtain();
        request.setAttribute("getList", articleList);
        response.setContentType("text/json;charset=utf-8");
        JSONObject jsonObject = new JSONObject();
        String data = jsonObject.toJSONString(articleList);
        System.out.println(articleList);
        response.getWriter().println(data);
    }

    //审核文章
    protected void reviewArticle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/json;charset=utf-8");
        System.out.println("审核文章");
        articleService = new ArticleServiceImpl();
        String[] articleIdArr = request.getParameterValues("articleId[]");
        int[] articleIdArrInt = Arrays.stream(articleIdArr).mapToInt(Integer::parseInt).toArray();
        System.out.println(articleIdArr);
        int result = articleService.reviewArticle(articleIdArrInt);
        LayuiResponseData data = new LayuiResponseData();
        data.setCode(result);
        data.setMsg(result != 0 ? "成功" : "失败");
        UserDao userDao = new UserDaoImpl();
        data.setCount(userDao.getUserNumber());
        data.setData(null);
        String jsonStr = JSON.toJSONString(data);
        response.getWriter().println(jsonStr);

    }

    //添加文章
    protected void addArticle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/json;charset=utf-8");
        JSONObject jsonObject = GetRequestJsonUtils.getRequestJsonObject(response, request);

        //获取标题对应的值
        String articleTitle = jsonObject.getString("articleTitle");
        System.out.println("articleTitle：" + articleTitle);

        //获取内容对应的值
        String articleContent = jsonObject.getString("articleContent");
        System.out.println("articleContent：" + articleContent);

        //获取作者对应的值
        String articleAuthor = jsonObject.getString("articleAuthor");
        System.out.println("articleAuthor：" + articleAuthor);

        //获取作者头像
        String authorImg=jsonObject.getString("author_img");
        System.out.println("author_img:"+authorImg);

        //生成时间
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        String time = formatter.format(date);
        //创建文章对象保存数据
        Article article = new Article();
        article.setArticleTitle(articleTitle);
        article.setArticleContent(articleContent);
        article.setArticleAuthor(articleAuthor);
        article.setAuthorImg(authorImg);
        article.setArticleTime(time);
        article.setArticleStatus("待审核");
        ArticleService articleService = new ArticleServiceImpl();
        result=articleService.addArticle(article);
        ArticleResposeData<Object> articleResposeData = new ArticleResposeData<Object>();
        articleResposeData.setCode(result==1?200:500);
        articleResposeData.setSuccess("发布成功");
        String jsonStr = JSON.toJSONString(articleResposeData);
        System.out.println(jsonStr);
        response.getWriter().println(jsonStr);
    }


    //根据类型拿到文章数据
    protected void getTypelookup(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取列表
        ArticleService articleService = new ArticleServiceImpl();
        List<Article> typeListArticle = articleService.getTypeLook();
        request.setAttribute("getList", typeListArticle);
        response.setContentType("text/json;charset=utf-8");
        JSONObject jsonObject = new JSONObject();
        String data = jsonObject.toJSONString(typeListArticle);
        response.getWriter().println(data);
    }

    //根据类型拿到文章数据
    protected void getTheArticleByType(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取列表
        ArticleService articleService = new ArticleServiceImpl();
        List<Article> typeListGetArticle = articleService.getTheArticleByType();
        request.setAttribute("getList", typeListGetArticle);
        response.setContentType("text/json;charset=utf-8");
        JSONObject jsonObject = new JSONObject();
        String data = jsonObject.toJSONString(typeListGetArticle);
        response.getWriter().println(data);
    }

    //根据类型拿到文章数据
    protected void getArticlesAccordingToProgram(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取列表
        ArticleService articleService = new ArticleServiceImpl();
        List<Article> articleaccordingList = articleService.getArticlesAccordingToProgram();
        request.setAttribute("getList", articleaccordingList);
        response.setContentType("text/json;charset=utf-8");
        JSONObject jsonObject = new JSONObject();
        String data = jsonObject.toJSONString(articleaccordingList);
        response.getWriter().println(data);
    }
    //根据用户id获取文章列表
    protected void getArticleListByUserId(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/json;charset=utf-8");
        ArticleService articleService = new ArticleServiceImpl();
        articleList=new ArrayList<Article>();
        articleList = articleService.getArticleListByUserId(request.getParameter("userId"));
        JSONObject jsonObject = new JSONObject();
        String data = jsonObject.toJSONString(articleList);
        response.getWriter().println(data);
    }

}
